package com.guochenglang.www.service.impl;

import com.guochenglang.www.service.AffairService;
import com.guochenglang.www.util.connect.ConnectManager;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务的封装
 *
 * @author 郭程朗
 */
public class AffairServiceImpl implements AffairService {
    /**
     * 获取连接池
     */
    private static final ConnectManager CONNECT_MANAGER = ConnectManager.getPool();

    /**
     * 开启事务
     */
    @Override
    public void startAffair() {
        try {
            //获得当前连接并开启事务
            Connection conn = CONNECT_MANAGER.getConnection();
            conn.setAutoCommit(false);
        } catch (InterruptedException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 事务提交
     */
    @Override
    public void commit() {
        try {
            //获取当前连接并提交
            Connection conn = CONNECT_MANAGER.getConnection();
            conn.commit();

        } catch (InterruptedException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 回滚
     */
    @Override
    public void rollback() {
        Connection conn = null;
        try {
            //获取当前连接并回滚
            conn = CONNECT_MANAGER.getConnection();
            conn.rollback();

        } catch (InterruptedException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 归还当前连接
     */
    @Override
    public void returnConnection() {
        try {
            CONNECT_MANAGER.returnConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
